/**
 * 
 */
package travibot.core;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import travibot.model.Village;
import travibot.utility.ValueExtractor;

/**
 * @author Petr
 * 
 */
public class VillagesParser extends GenericParser {

    private static Logger log = Logger.getLogger(VillagesParser.class);

    private List<Village> list;

    public List<Village> getVillages() {

        if (list == null) {
            list = new ArrayList<Village>();
            parseRecursive(super.getDocument());
        }

        return list;
    }

    private void parseRecursive(Node node) {

        String nodeName = node.getNodeName().toLowerCase();

        // lets parse the buildings
        if (nodeName.equals("a")) {
            NamedNodeMap attributes = node.getAttributes();
            Node name = attributes.getNamedItem("href");
            if (name.getNodeValue().indexOf("dorf1.php?") != -1) {
                addVillage(node);
            }
        }

        Node child = node.getFirstChild();
        while (child != null) {

            parseRecursive(child);
            child = child.getNextSibling();
        }
    }

    private void addVillage(Node node) {

        NamedNodeMap attributes = node.getAttributes();
        Node href = attributes.getNamedItem("href");
        if(href != null){
            String[] parts = href.getNodeValue().split("php");
            if(parts.length == 2){
                int id = Integer.parseInt(ValueExtractor.getNumericValueOnly(parts[1]));
                String name = node.getTextContent();
                Village village = new Village(id);
                village.setName(name);
                list.add(village);
            }
        }        
    }

}
